/*
 * ProgramStreamParser.h
 *
 *  Created on: 2015年7月5日
 *      Author: terry
 */

#ifndef PROGRAMSTREAMPARSER_H_
#define PROGRAMSTREAMPARSER_H_

#include "MediaPacket.h"
#include "H264NaluParser.h"
#include "TIOBuffer.h"


namespace av
{

/**
 * PS节目流解析器, 实现从字节流解析出媒体包
 */
class ProgramStreamParser
{
public:
    typedef unsigned char   uint8_t;

    struct StreamPacket
    {
        uint8_t*    data;
        size_t      length;
        uint8_t     type;
    };

public:
    ProgramStreamParser();
    virtual ~ProgramStreamParser();

    /**
     * 输入字节流, 获取媒体包
     * @param data	字节数组指针
     * @param length	字节数组长度
     * @param pkt
     * @return true 表示有解析出媒体包
     */
    bool inputData(const uint8_t* data, size_t length, StreamPacket& pkt);

    /**
     * 重置清理
     */
    void clear();


protected:
    bool handlePacket(StreamPacket& packet);

    virtual void writePacket(NaluPacket& packet);

    bool onPESPacket(StreamPacket& packet);

    bool flushPacketBuffer();


    size_t findStartCode(const uint8_t* buffer, size_t length);

    size_t findStartCode(const uint8_t* buffer, size_t offset, size_t length);

    bool ensureStartCode(comn::IOBuffer& buffer);

    size_t findHeaderStartCode(const uint8_t* buffer, size_t offset, size_t length);



private:
    comn::IOBuffer      m_cache;

    uint8_t m_lastType;
    comn::IOBuffer    m_pktBuffer;

    StreamPacket	m_naluPkt;
    comn::IOBuffer	m_naluBuffer;

};


} /* namespace av */

#endif /* PROGRAMSTREAMPARSER_H_ */
